import { defineStore } from 'pinia'
import { reactive } from 'vue'
import type { LoginForm } from '@/api/user/type';
import { constantRoutes, asyncRoutes, anyRoutes } from '@/route/routes';
import { useroutes } from './routes';
import cloneDeep from 'lodash/cloneDeep';
import router from '@/route';
import { login, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api/user';
import type { LoginInfoData, UserInfoData } from '@/api/user/type';
export const useUserStore = defineStore('user', () => {
    const userInfo = reactive({
        avatar: '',
        username: '',
        desc: '',
        roles: [] as string[],
        buttons: [] as string[],
        routes: [] as string[],
        token: localStorage.getItem('token') as string,
    });
    async function userlogin(data: LoginForm) {
        const res: LoginInfoData = await login(data);
        console.log(res);
        if (res.code === 200 && res.data) {
            let token = '';
            token = res.data as string;
            localStorage.setItem('token', token);
            userInfo.token = token;
            try {
                await getUserInfo();
            } catch (error) {
                return Promise.reject(new Error('获取用户信息失败a'));
            }
            return Promise.resolve('ok');
        }
        else {
            return Promise.reject(new Error(res.message || '登录失败'));
        }
    }
    async function getUserInfo() {
        const res: UserInfoData = await getUserInfoApi();
        if (res.code === 200) {
            userInfo.avatar = res.data.avatar;
            userInfo.username = res.data.name;
            userInfo.roles = res.data.roles;
            userInfo.buttons = res.data.buttons;
            userInfo.routes = res.data.routes;
            //深拷贝,防止修改原异步路由
            const UseAsnycRoutes = cloneDeep(asyncRoutes);
            let filteruseroutes = filterRoutes(UseAsnycRoutes, userInfo.routes)
            const useroute = useroutes();
            [...filteruseroutes, ...anyRoutes].forEach(element => {
                router.addRoute(element)
            });
            useroute.routexs = [...constantRoutes, ...filteruseroutes, ...anyRoutes]
        }
        else {
            return Promise.reject(new Error('获取用户信息失败b'));
        }
    }
    async function logout() {
        const res: any = await logoutApi();
        if (res.code == 200) {
            localStorage.removeItem('token');
            userInfo.avatar = '';
            userInfo.username = '';
            userInfo.desc = '';
            userInfo.roles = [] as string[];
            userInfo.buttons = [] as string[];
            userInfo.routes = [] as string[];
            userInfo.token = '';
            return Promise.resolve('ok');
        }
        else {
            return Promise.reject(new Error('退出失败'));
        }
    }
    const filterRoutes = (asyncRoutes: any[], routes: any[]) => {
        return asyncRoutes.filter((item: any) => {
            if (routes.includes(item.name)) {
                if (item.children && item.children.length > 0) {
                    item.children = filterRoutes(item.children, routes)
                }
                return true
            }
        })
    }
    return {
        userInfo,
        userlogin,
        getUserInfo,
        logout
    }
})


